import { login, logout, getUserInfo } from "@/api/user"
import { getToken, setToken, removeToken } from "@/utils/token"

const state = {
  token: getToken(),
  userInfo: {},
  username: "",
  avatar: ""
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, data) => {
    state.userInfo = data
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit("SET_TOKEN", data.token)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        });
    })
  },

  saveToken({ commit }, token) {
    return new Promise(resolve => {
      commit("SET_TOKEN", token)
      setToken(token)
      resolve()
    });
  },

  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo({
        token: state.token
      })
        .then(response => {
          const { data } = response
          if (!data) {
            reject("认证失败，请重新登录");
          }
          resolve(response.data)
        })
        .catch(error => {
          reject(error)
        });
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit("SET_TOKEN", "")
          removeToken()
          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch("tagsView/delAllViews", null, { root: true })
          resolve()
        })
        .catch(error => {
          reject(error)
        });
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "")
      removeToken()
      resolve()
    });
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
